import React, { useEffect, useState } from 'react'
import { Table, Form, Button, Input, Divider, message, ConfigProvider, Row, Col, Modal } from 'antd'
import { loginApi } from '~/api/login-api'
import zhCN from 'antd/es/locale/zh_CN'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { itemList } from '~/api/query-api'
import { deleteItems } from '~/api/collection-api'
import { getAllUrlParam, handleGetItem, formatTime, deepFlatten } from '~/utils/utils'
import CollectionModal from './CollectionModal'
import { MODALTYPE, itemSource } from '~/constants'
import PopoverColumn from '~/components/popover-column'
import useGetAllConfig from '~/hooks/useGetAllConfig'
import { queryDetail } from '~/api/upload-item-api'
import { batchGetTmpHttpUrl } from '~/api/store-file-api'

const colums: any = ({
  onClickView,
  onClickViewImage,
  onClickEdit,
  onClickDelete,
  handleGetItem,
  flatItemArr
}: any) => [
  {
    title: '序号',
    dataIndex: 'id',
    align: 'center',
    render: (_: any, record: any, index: number) => <div>{index + 1}</div>
  },
  {
    title: '案件编号',
    dataIndex: 'caseNo',
    align: 'center',
    render: (caseNo: any, record: any) => (
      <PopoverColumn record={record}>
        <a>{caseNo}</a>
      </PopoverColumn>
    )
  },
  {
    title: '物品编号',
    dataIndex: 'serialNo',
    align: 'center'
    // render: (caseNo: any, record: any) => (
    //   <PopoverColumn record={record}>
    //     <a>{caseNo}</a>
    //   </PopoverColumn>
    // )
  },
  {
    title: '物品名称',
    dataIndex: 'itemName',
    align: 'center'
  },
  {
    title: '物品数量',
    align: 'center',
    dataIndex: 'itemStock',
    render: (itemName: any, record: any) => (
      <div>
        {record.itemStock.totalNumber} ({record.itemStock.unitName})
      </div>
    )
  },
  {
    title: '持有人',
    align: 'center',
    dataIndex: 'holderUserName',
    key: 'holderUserName'
  },
  {
    title: '物品来源',
    align: 'center',
    dataIndex: 'acquireWay',
    render: (acquireWay: any) => <div>{itemSource.get(acquireWay)}</div>
  },
  {
    title: '物品分类',
    align: 'center',
    dataIndex: 'itemClass',
    render: (_: any, record: any) => <div>{handleGetItem(flatItemArr, record)}</div>
  },
  {
    title: '登记时间',
    align: 'center',
    dataIndex: 'createTime',
    render: (createTime: any) => createTime && formatTime(createTime)
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    key: 'action',
    render: (_: any, record: any) => (
      <div>
        <a onClick={() => onClickView(record)}>查看</a>
        <Divider type="vertical" />
        <a onClick={() => onClickEdit(record)}>编辑</a>
        <Divider type="vertical" />
        <a onClick={() => onClickViewImage(record)}>物品照片</a>
        <Divider type="vertical" />
        <a onClick={() => onClickDelete(record)}>删除</a>
      </div>
    )
  }
]

const CollectionList = () => {
  const { data: configData = {} } = useGetAllConfig()
  const { itemCategory = [] } = configData
  const flatItemArr: any = (configData && deepFlatten(itemCategory)).concat(itemCategory)

  const [form] = Form.useForm()
  const { resetFields } = form
  const { userNo, ajbh, ajmc, jqbh } = getAllUrlParam()
  const [waitList, setWaitList] = useState([])
  const [imgList, setImgList] = useState([])
  const [visible, setVisible] = useState(false)
  const [imgVisible, setImgVisible] = useState(false)

  const [record, setRecord] = useState({})
  const [modalType, setModalType] = useState<any>('')

  const handleSetLoginInfo = async (loginid: any) => {
    const res = await loginApi({
      ticket: loginid
    })
    localStorage.setItem('u', JSON.stringify(res))
    return res
  }

  const onClickSearchItems = async (values?: any) => {
    const { data } = await itemList({
      ...values,
      caseNo: ajbh,
      caseName: decodeURIComponent(ajmc),
      jqbh,
      needItemOnlineStatus: false
    })
    setWaitList(data)
  }

  const onClickViewImage = async (record: any) => {
    const { data } = await queryDetail({ serialNo: record.serialNo })
    if (!data.length) return message.info('无相关图片')
    const storeIds = data.map((item: any) => item.storeId)
    const res = await batchGetTmpHttpUrl(storeIds)
    setImgList(res.data)
    setImgVisible(true)
  }

  const onClickView = (record: any) => {
    setVisible(true)
    setModalType(MODALTYPE.view)
    setRecord(record)
  }

  const onClickEdit = (record: any) => {
    setVisible(true)
    setModalType(MODALTYPE.edit)
    setRecord(record)
  }

  const onClickCreate = () => {
    setVisible(true)
    setModalType(MODALTYPE.create)
  }

  const onClickDelete = async (record: any) => {
    await deleteItems({ serialNo: record.serialNo, userNo })
    message.success(`删除${record.itemName}成功`)
    onClickSearchItems()
  }

  useEffect(() => {
    moment.locale('zh-cn')
    if (
      !localStorage.getItem('u') ||
      (localStorage.getItem('u') && !JSON.parse(localStorage.getItem('u')!).roles) ||
      userNo ||
      userNo
    ) {
      handleSetLoginInfo(userNo).then(() => {
        onClickSearchItems()
      })
    } else {
      onClickSearchItems()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <ConfigProvider locale={zhCN} componentSize="middle">
      <div style={{ padding: 24 }}>
        <Form
          validateTrigger="onBlur"
          layout="inline"
          form={form}
          style={{ marginBottom: 16 }}
          onFinish={onClickSearchItems}
        >
          <Form.Item name="itemName" label="物品名称：">
            <Input placeholder="请输入物品名称搜索" />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button
            onClick={() => {
              resetFields()
              onClickSearchItems()
            }}
            type="link"
            style={{ marginLeft: 10 }}
          >
            清空选项
          </Button>
          <Button onClick={onClickCreate} style={{ marginLeft: 10 }}>
            新增物品
          </Button>
        </Form>
        <Table
          bordered
          rowKey="id"
          dataSource={waitList}
          pagination={{
            size: 'default',
            total: waitList ? waitList.length : 0,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条`
          }}
          columns={colums({ onClickView, onClickEdit, onClickViewImage, onClickDelete, handleGetItem, flatItemArr })}
        />
        <CollectionModal
          onClickSearchItems={onClickSearchItems}
          record={record}
          setSelectVisible={setVisible}
          modalType={modalType}
          visible={visible}
        />
        <Modal
          footer={null}
          onCancel={() => {
            setImgVisible(false)
          }}
          width={'max-content'}
          visible={imgVisible}
        >
          <Row>
            {imgList.map((item: any, index: number) => (
              <Col span={12} key={index} style={{ padding: 24 }}>
                <img style={{ width: 300 }} src={item.tmpHttpUrl} />
              </Col>
            ))}
          </Row>
        </Modal>
      </div>
    </ConfigProvider>
  )
}

export default CollectionList
